<template>
	
	<!-- 
	 1.画出图片
	 2.转成两个图片网址
	 3.图片合并
	 -->
	<view>
		<image :src="path" mode="widthFix" style="width:100vw;"></image>
		<button type="default" @click="getbase64ImgDetail">合成</button>
		<image :src="post_img" mode="widthFix" class='poster' style="width: 100vw;" :show-menu-by-longpress="true"></iage>
		
		<!-- //画布 -->
		<canvas canvas-id="shareCanvas" class="canvas" bindlongpress="saveImg" catchtouchmove="true":style="{height: canvasHeight+'rpx',width:canvasWidth+'rpx'}" ></canvas>
		<view style="width: 100vw;">
			<l-painter  isCanvasToTempFilePath @success="path = $event" hidden
			  css="background: #fff;box-sizing: border-box;">
			   <l-painter-image :src="detail.productImg" css="width: 100vw;border:1rpx #f00 solid;"/>
			   <l-painter-view css="margin:20rpx;">
				   <l-painter-text :text="tip" css="display:block; color: #000; font-size: 24rpx; height:40rpx;line-height:40rpx;"/>
				   <l-painter-text :text="detail.productName" css="display:block; color: #000; font-size: 44rpx; height:60rpx;line-height:60rpx;fontWeight: bold;"/>
				   			  
				   <l-painter-view css="display:flex;flex-dection:row;align-items: center;justify-content: center;">
					  <l-painter-view css="margin-top:20rpx;box-sizing: border-box;width:70%;height:120rpx;line-height:120rpx;text-align:center;background:#ff6700;color:#fff;border-radius: 20rpx;font-size:50rpx;">
						<l-painter-text :text="today+type+'¥'+detail.productPrice" />
					  </l-painter-view>
				   </l-painter-view>
			   </l-painter-view>
			   
			 
			</l-painter>
		 </view>
		
		
		
		
	</view>
</template>
<script>
export default {
	data(){
		return {
			path:'',
			detail:{
				productImg:'https://univs-news-1256833609.file.myqcloud.com/resource_files/cont_pub/I/AIJOI/J3SLIQIDP5BOND3A2T57W6BTOI.png',
				productName:'中华（硬）',
				id:1,
				productPrice:393.0,
			},
			tip:'长按识别长按识别长按识别长按识别长按识别按识别',
			xdata:[],
			ydata:[],
			today:'23日',
			type:'出货',
			
			
			ctx:null,
			windowObj:{},
			codePng:"https://img0.baidu.com/it/u=2246390317,2262354076&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500", //折线图
			post_img:'',
			canvasHeight:'',
			canvasWidth:'',
			url:'',
			
							
		}
	},
	onReady(){
		//初始化画布
		this.ctx = wx.createCanvasContext('shareCanvas');
		
	},
	methods:{
		//获取图片的基本信息，即将网络图片转成本地图片，
		getImageInfo(src) {
			return new Promise((resolve, reject) => {
				wx.getImageInfo({
					src,
					success: (res) =>{
						console.log("图片信息",res);
						resolve(res);
					} ,
					fail: (res) => {
						console.log("失败图拍品系",res);
						reject(res)
					},
					
				})
			});
		},
		base64ToPng(base64Data, successCallback, failCallback) {
		  const fs = uni.getFileSystemManager();
		  const filePath = `${uni.env.USER_DATA_PATH}/temp_image.png`; // 指定保存图片的路径 http://usr/temp_image.png
		  // 去掉Base64的数据头部信息
		  const base64 = base64Data.split(',')[1];
		  const buffer = uni.base64ToArrayBuffer(base64);
		  
		  fs.writeFile({
		    filePath: filePath,
		    data: buffer,
		    encoding: 'binary',
		    success: (res) => {
		      if (successCallback) {
		        successCallback(filePath);
		      }
		    },
		    fail: (err) => {
		      if (failCallback) {
		        failCallback(err);
		      }
		    }
		  });
		},
		getbase64ImgDetail(){
			this.base64ToPng(this.path, (filePath) => {
			  console.log('图片保存成功，文件路径：', filePath);
			  this.url=filePath;
			  this.exportPost();
			}, (err) => {
			  console.error('图片保存失败：', err);
			});
			
			
		},
		exportPost(){
			let that  =  this
			uni.showLoading({
				title:'海报生成中'
			})
			
			
		//image是画布的底图，后期可以换成自己需要的
			let image =this.url;
			console.log("image",image);
			//获取系统的基本信息，为后期的画布和底图适配宽高
			 uni.getSystemInfo({
				success: function (res0) {
				that.windowObj = res0 
				that.windowObj.ratio = that.windowObj.windowWidth/750 //因为小程序是用rpx单位，为了是后期合成的图片更好是适应各个手机屏幕的尺寸，这里先计算出一个比率，后面除以这个比率就可以对各个手机尺寸进行适配了
				that.canvasWidth = that.windowObj.windowWidth/that.windowObj.ratio //设置画布的宽高
				that.canvasHeight = that.windowObj.windowHeight/that.windowObj.ratio
				Promise.all([that.getImageInfo(image),that.getImageInfo(that.codePng),]).then(res=>{ //that.getImageInfo(that.page_data.codePng)
					console.log("图片",res);
		          //获取底图和二维码图片的基本信息,通常前端导出的二维码是base64格式的，所以要转成图片格式的才可以获取图片的基本信息			
			
				let arr = [
					{width:res[0].width,height:res[0].height},
					// {width:res[0].width/that.windowObj.pixelRatio/2,height:res[0].height/that.windowObj.pixelRatio/2},
					{width:res[1].width,height:res[1].height},
				]
				console.log("arr",arr);
				// that.ctx.drawImage(res[0].path,0 , 0,that.windowObj.windowWidth,res[0].height*that.windowObj.ratio);
				// that.ctx.drawImage(res[1].path, (that.windowObj.windowWidth-arr[1].width)/2, (that.windowObj.windowHeight-arr[1].height)-30,arr[1].width,arr[1].height);
				that.ctx.drawImage(res[0].path,0 , 0,that.windowObj.windowWidth,res[0].height*that.windowObj.ratio);
				that.ctx.drawImage(res[1].path, 0, (that.windowObj.windowHeight-arr[1].height)-30,that.windowObj.windowWidth,100);
					  that.ctx.draw(false,function(){
						  wx.canvasToTempFilePath({
							  x: 0,
							  y: 0,
							  width:that.windowObj.windowWidth,
							  height:that.windowObj.windowHeight,
							  destWidth:that.windowObj.windowWidth*2,//这里乘以2是为了保证合成图片的清晰度
							  destHeight:that.windowObj.windowHeight*2,
							  canvasId: 'shareCanvas',
							  fileType:'jpg',//设置导出图片的后缀名
							  success: function (res) {
								  uni.hideLoading();
								  console.log("合成后的图片",res.tempFilePath);
								  let list=[];
								  list.push(res.tempFilePath);
								  uni.previewImage({
								  	 urls: list, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了       
								  	 success: function(res) { 
								  		  // that.closeDialog();
								  	 }
								  	
								   })
							  }
						  })   
					  });
					})     
					
					
					
					
				}
			})
		},
	},
}
</script>
<style>
	.wp{
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		border-radius: 20rpx;
	}
</style>